<template>
  <view class="reviews-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏（固定定位） -->
    <view class="top-nav" :style="{ top: statusBarHeight + 'px' }">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">商家评价</text>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 商家信息卡片 -->
    <view v-if="merchantInfo" class="merchant-card">
      <view class="merchant-header">
        <image 
          v-if="merchantInfo.logo" 
          :src="merchantInfo.logo" 
          class="merchant-logo"
          mode="aspectFill"
        />
        <view class="merchant-info">
          <text class="merchant-name">{{ merchantInfo.name }}</text>
          <view class="rating-info">
            <StarRating :value="merchantInfo.rating" :readonly="true" :size="32" />
            <text class="rating-text">{{ merchantInfo.rating }}分</text>
            <text class="review-count">({{ statistics.totalReviews }}条评价)</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view 
        class="filter-item"
        :class="{ active: currentFilter === 'all' }"
        @click="setFilter('all')"
      >
        <text class="filter-text">全部</text>
      </view>
      <view 
        class="filter-item"
        :class="{ active: currentFilter === 5 }"
        @click="setFilter(5)"
      >
        <text class="filter-text">5星</text>
      </view>
      <view 
        class="filter-item"
        :class="{ active: currentFilter === 4 }"
        @click="setFilter(4)"
      >
        <text class="filter-text">4星</text>
      </view>
      <view 
        class="filter-item"
        :class="{ active: currentFilter === 'hasImage' }"
        @click="setFilter('hasImage')"
      >
        <text class="filter-text">有图</text>
      </view>
    </view>

    <!-- 评价列表 -->
    <view class="reviews-list">
      <view 
        v-for="(review, index) in reviews" 
        :key="index"
        class="review-card"
      >
        <view class="review-header">
          <image 
            v-if="review.userAvatar"
            :src="review.userAvatar" 
            class="user-avatar"
            mode="aspectFill"
            @error="onAvatarError($event, index)"
          />
          <view v-else class="user-avatar-placeholder">
            <text class="avatar-text">{{ getAvatarText(review.username) }}</text>
          </view>
          <view class="user-info">
            <text class="username">{{ review.username }}</text>
            <view class="rating-row">
              <StarRating :value="review.overallRating" :readonly="true" :size="28" />
            </view>
          </view>
          <text class="review-date">{{ formatDate(review.createdAt) }}</text>
        </view>

        <view v-if="review.content" class="review-content">
          <text class="content-text">{{ review.content }}</text>
        </view>

        <view v-if="review.tags && review.tags.length > 0" class="review-tags">
          <view 
            v-for="(tag, tagIndex) in review.tags" 
            :key="tagIndex"
            class="tag"
          >
            <text class="tag-text">{{ tag }}</text>
          </view>
        </view>

        <view v-if="review.images && review.images.length > 0" class="review-images">
          <image 
            v-for="(image, imgIndex) in review.images" 
            :key="imgIndex"
            :src="image"
            class="review-image"
            mode="aspectFill"
            @click="previewImage(review.images, imgIndex)"
          />
        </view>

        <view v-if="review.merchantReply" class="merchant-reply">
          <view class="reply-header">
            <text class="reply-icon">💬</text>
            <text class="reply-label">商家回复：</text>
          </view>
          <text class="reply-content">{{ review.merchantReply }}</text>
          <text class="reply-date">{{ formatDate(review.merchantReplyAt) }}</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && reviews.length === 0" class="empty-state">
        <text class="empty-icon">📝</text>
        <text class="empty-text">暂无评价</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more">
        <text class="load-more-text">{{ loadingMore ? '加载中...' : '上拉加载更多' }}</text>
      </view>

      <!-- 没有更多 -->
      <view v-if="!hasMore && reviews.length > 0" class="no-more">
        <text class="no-more-text">没有更多了</text>
      </view>
    </view>
  </view>
</template>

<script>
import StarRating from '@/components/StarRating.vue';
import reviewService from '@/services/review.js';
import api from '@/services/api.js';
import { backToHome } from '@/utils/navigation.js';

export default {
  components: {
    StarRating
  },
  data() {
    return {
      statusBarHeight: 0,
      merchantId: null,
      merchantInfo: null,
      reviews: [],
      statistics: {
        totalReviews: 0,
        averageRating: 0
      },
      currentFilter: 'all',
      page: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      loadingMore: false
    };
  },
  onLoad(options) {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 0;
    
    // 设置 CSS 变量（用于固定导航栏定位）
    // #ifdef H5
    if (typeof document !== 'undefined') {
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px');
    }
    // #endif

    this.merchantId = options.merchantId;
    if (!this.merchantId) {
      uni.showToast({ title: '商家ID不存在', icon: 'none' });
      return;
    }

    this.loadMerchantInfo();
    this.loadReviews();
  },
  onReachBottom() {
    if (this.hasMore && !this.loadingMore) {
      this.loadMore();
    }
  },
  onPullDownRefresh() {
    this.page = 1;
    this.reviews = [];
    this.hasMore = true;
    this.loadReviews().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    // 返回（智能返回，刷新后自动跳转首页）
    goBack() {
      backToHome();
    },

    // 加载商家信息
    async loadMerchantInfo() {
      try {
        const res = await api.get(`/merchants/${this.merchantId}`, {}, { needAuth: false });
        if (res.code === 200 && res.data) {
          this.merchantInfo = res.data;
        }
      } catch (error) {
        console.error('加载商家信息失败:', error);
      }
    },

    // 加载评价列表
    async loadReviews() {
      if (this.loading) return;

      try {
        this.loading = true;

        const params = {
          page: this.page,
          size: this.pageSize
        };

        // 添加筛选条件
        if (this.currentFilter !== 'all') {
          if (this.currentFilter === 'hasImage') {
            params.hasImage = true;
          } else {
            params.rating = this.currentFilter;
          }
        }

        const res = await reviewService.getMerchantReviews(this.merchantId, params);
        
        // 格式化评价数据
        const formattedReviews = (res.data.items || []).map(review => {
          return {
            ...review,
            // 优先使用真实姓名，其次用户名
            username: review.realName || review.userRealName || review.user_real_name || 
                     review.username || review.user_name || review.userName || '匿名用户',
            userAvatar: review.userAvatar || review.user_avatar || review.avatar || null,
            overallRating: review.overallRating || review.overall_rating || review.rating || 5,
            createdAt: review.createdAt || review.created_at || review.createTime,
            merchantReply: review.merchantReply || review.merchant_reply || review.reply,
            merchantReplyAt: review.merchantReplyAt || review.merchant_reply_at || review.replyTime
          };
        });
        
        if (this.page === 1) {
          this.reviews = formattedReviews;
        } else {
          this.reviews = [...this.reviews, ...formattedReviews];
        }

        this.statistics = res.data.statistics || { totalReviews: 0, averageRating: 0 };
        this.hasMore = this.reviews.length < (res.data.total || 0);
      } catch (error) {
        console.error('加载评价列表失败:', error);
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 加载更多
    async loadMore() {
      if (this.loadingMore || !this.hasMore) return;

      this.loadingMore = true;
      this.page++;
      await this.loadReviews();
      this.loadingMore = false;
    },

    // 设置筛选条件
    setFilter(filter) {
      this.currentFilter = filter;
      this.page = 1;
      this.reviews = [];
      this.hasMore = true;
      this.loadReviews();
    },

    // 预览图片
    previewImage(images, index) {
      uni.previewImage({
        urls: images,
        current: index
      });
    },
    
    // 头像加载失败处理
    onAvatarError(event, index) {
      console.log('头像加载失败:', this.reviews[index].userAvatar);
      // 将该评价的头像设为null，显示占位符
      this.reviews[index].userAvatar = null;
      this.$forceUpdate();
    },
    
    // 获取用户名首字母作为头像文字
    getAvatarText(username) {
      if (!username) return '?';
      // 如果是中文，取第一个字
      if (/[\u4e00-\u9fa5]/.test(username)) {
        return username.charAt(0);
      }
      // 如果是英文，取首字母大写
      return username.charAt(0).toUpperCase();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const now = new Date();
      const diff = now - date;
      
      // 一分钟内
      if (diff < 60000) {
        return '刚刚';
      }
      // 一小时内
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前';
      }
      // 一天内
      if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前';
      }
      // 一周内
      if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前';
      }
      
      // 超过一周显示具体日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.reviews-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 40rpx;
}

/* 状态栏占位 */
.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #FFFFFF;
  z-index: 999;
}

/* 导航栏（固定定位） */
.top-nav {
  position: fixed;
  top: var(--status-bar-height, 0px);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background: #FFFFFF;
  border-bottom: 1rpx solid #EEEEEE;
  z-index: 998;
}

.nav-left, .nav-right {
  width: 120rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #333333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

/* 商家卡片 */
.merchant-card {
  margin-top: calc(var(--status-bar-height, 0px) + 88rpx + 20rpx);
  margin-left: 30rpx;
  margin-right: 30rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.merchant-header {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.merchant-logo {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.merchant-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.merchant-name {
  font-size: 34rpx;
  font-weight: 600;
  color: #333333;
}

.rating-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.rating-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #FF6B6B;
}

.review-count {
  font-size: 26rpx;
  color: #999999;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background: #FFFFFF;
  border-bottom: 1rpx solid #EEEEEE;
}

.filter-item {
  padding: 12rpx 32rpx;
  background: #F5F5F5;
  border-radius: 40rpx;
  transition: all 0.3s ease;
}

.filter-item.active {
  background: #FF6B6B;
}

.filter-text {
  font-size: 28rpx;
  color: #666666;
}

.filter-item.active .filter-text {
  color: #FFFFFF;
}

/* 评价列表 */
.reviews-list {
  padding: 20rpx 30rpx;
}

.review-card {
  margin-bottom: 20rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.review-header {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #F0F0F0;
}

.user-avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #FFFFFF;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.username {
  font-size: 30rpx;
  font-weight: 600;
  color: #333333;
}

.rating-row {
  display: flex;
  align-items: center;
}

.review-date {
  font-size: 24rpx;
  color: #999999;
}

.review-content {
  margin-bottom: 20rpx;
}

.content-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
}

.review-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.tag {
  padding: 8rpx 20rpx;
  background: #FFF5F5;
  border-radius: 20rpx;
}

.tag-text {
  font-size: 24rpx;
  color: #FF6B6B;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.review-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
}

.merchant-reply {
  margin-top: 20rpx;
  padding: 20rpx;
  background: #F8F8F8;
  border-radius: 12rpx;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 12rpx;
}

.reply-icon {
  font-size: 28rpx;
}

.reply-label {
  font-size: 26rpx;
  font-weight: 600;
  color: #666666;
}

.reply-content {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
}

.reply-date {
  font-size: 22rpx;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-more-text {
  font-size: 26rpx;
  color: #999999;
}

.no-more {
  text-align: center;
  padding: 40rpx 0;
}

.no-more-text {
  font-size: 26rpx;
  color: #CCCCCC;
}
</style>

